package org.xiyu.yee.pjwto.trading;

import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.entity.monster.piglin.Piglin;
import net.minecraft.world.inventory.MerchantMenu;
import net.minecraft.world.item.trading.Merchant;
import net.minecraft.world.item.trading.MerchantOffer;
import net.minecraft.world.item.trading.MerchantOffers;
import net.minecraft.world.entity.player.Player;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.Nullable;
import org.xiyu.yee.pjwto.Constants;

/**
 * 猪灵交易界面管理类
 */
public class PiglinTradeMenu {
    
    /**
     * 为玩家打开猪灵交易界面
     */
    public static void openTradeMenu(Piglin piglin, ServerPlayer player) {
        Constants.LOG.info("Opening piglin trade menu for player: {}", player.getName().getString());
        
        // 生成交易数据
        MerchantOffers offers = PiglinTradeManager.generateTrades(piglin, player);
        Constants.LOG.info("Generated {} offers for piglin trading", offers.size());
        
        // 创建猪灵商人包装器
        PiglinMerchant merchant = new PiglinMerchant(piglin, player, offers);
        
        // 设置交易玩家
        merchant.setTradingPlayer(player);
        
        // 打开交易界面
        player.openMenu(merchant);
        
        // 立即发送交易数据包
        sendTradeDataToClient(player, player.containerMenu.containerId, offers);
    }
    
    /**
     * 发送交易数据到客户端
     */
    private static void sendTradeDataToClient(ServerPlayer player, int containerId, MerchantOffers offers) {
        try {
            Constants.LOG.info("Sending {} trade offers to client (container: {})", offers.size(), containerId);
            
            // 创建并发送商人交易数据包
            ClientboundMerchantOffersPacket packet = new ClientboundMerchantOffersPacket(
                containerId,                       // 容器ID
                offers,                            // 交易列表
                0,                                 // 村民等级
                0,                                 // 村民经验
                false,                             // 是否显示进度条
                false                              // 是否可以重新评估
            );
            
            player.connection.send(packet);
            Constants.LOG.info("Successfully sent trade packet to client");
        } catch (Exception e) {
            Constants.LOG.error("Failed to send trade packet to client", e);
        }
    }
    
    /**
     * 猪灵商人实现类，包装猪灵使其可以像村民一样交易
     */
    private static class PiglinMerchant implements Merchant, MenuProvider {
        private final Piglin piglin;
        private final ServerPlayer player;
        private final MerchantOffers offers;
        private Player tradingPlayer;
        
        public PiglinMerchant(Piglin piglin, ServerPlayer player, MerchantOffers offers) {
            this.piglin = piglin;
            this.player = player;
            this.offers = offers;
        }
        
        // MenuProvider 接口方法
        @Override
        public Component getDisplayName() {
            return Component.translatable("entity.minecraft.piglin");
        }
        
        @Override
        public net.minecraft.world.inventory.AbstractContainerMenu createMenu(int id, net.minecraft.world.entity.player.Inventory inventory, Player player) {
            return new MerchantMenu(id, inventory, this);
        }
        
        @Override
        public void setTradingPlayer(@Nullable Player player) {
            this.tradingPlayer = player;
        }
        
        @Nullable
        @Override
        public Player getTradingPlayer() {
            return this.tradingPlayer;
        }
        
        @Override
        public MerchantOffers getOffers() {
            return this.offers;
        }
        
        @Override
        public void overrideOffers(MerchantOffers offers) {
            // 不允许覆盖交易
        }
        
        @Override
        public void notifyTrade(MerchantOffer offer) {
            // 交易完成时的处理
            offer.increaseUses();
            this.piglin.ambientSoundTime = -this.piglin.getAmbientSoundInterval();
            this.rewardTradeXp(offer);
        }
        
        private void rewardTradeXp(MerchantOffer offer) {
            if (offer.shouldRewardExp()) {
                int experience = 3 + this.player.getRandom().nextInt(4);
                this.player.giveExperiencePoints(experience + offer.getXp());
            }
        }
        
        @Override
        public void notifyTradeUpdated(ItemStack stack) {
            // 交易更新时的处理
        }
        
//        @Override
//        public Level getLevel() {
//            return this.piglin.level();
//        }
        
        @Override
        public int getVillagerXp() {
            return 0;
        }
        
        @Override
        public void overrideXp(int xp) {
            // 不允许覆盖经验
        }
        
        @Override
        public boolean showProgressBar() {
            return false;
        }
        
        @Override
        public SoundEvent getNotifyTradeSound() {
            return SoundEvents.PIGLIN_AMBIENT;
        }
        
        @Override
        public boolean isClientSide() {
            return this.piglin.level().isClientSide;
        }
    }
}
